<template>
  <view class="container">
    <view class="img-a">
      <view class="t-b">
        您好，
        <br />
        欢迎使用，胎管家仓库端小程序
      </view>
    </view>
    <view class="login-view">
      <view class="t-login">
        <!-- 标题栏 -->
        <view class="head-box ss-m-b-60 ss-flex-col">
          <view class="ss-flex ss-m-b-20">
            <view class="head-title ss-m-r-40 head-title-animation">账号登录</view>
          </view>
          <view class="head-subtitle">如果未设置过密码，请联系管理员获取密码</view>
        </view>

        <!-- 表单项 -->
        <uni-forms
          ref="accountLoginRef"
          v-model="state.model"
          :rules="state.rules"
          validateTrigger="bind"
          labelWidth="140"
          labelAlign="center"
        >
          <uni-forms-item name="username" label="账号">
            <uni-easyinput
              placeholder="请输入账号"
              v-model="state.model.username"
              :inputBorder="false"
            >
            </uni-easyinput>
          </uni-forms-item>

          <uni-forms-item name="password" label="密码">
            <uni-easyinput
              type="password"
              placeholder="请输入密码"
              v-model="state.model.password"
              :inputBorder="false"
            >
            </uni-easyinput>
          </uni-forms-item>
        </uni-forms>

        <view><button @click="submitLogin" class="login-button">登录</button></view>

        <view style="width: 100%; height: 20px">&nbsp;</view>
        <view>
          <checkbox-group @change="handleCheckboxChange">
            <label style="font-size: 22rpx;font-weight: 400;">
              <checkbox :checked="false" :value="true" style="transform:scale(0.7)"/>
              我已阅读并遵守<span @click.stop="navigateToPage('/pages/login-pages/agreement')" class="tcp-text">《用户服务协议》</span>与<span @click.stop="navigateToPage('/pages/login-pages/policy')" class="tcp-text">《隐私协议》</span>
            </label>
          </checkbox-group>
        </view>
      </view>
    </view>
  </view>
</template>
<script setup>
  import { ref, reactive, onMounted, onUnmounted } from 'vue';
  import AuthUtil from '@/sheep/api/member/auth';
  import { DictUtils } from '@/sheep/store/DictUtils';

  const accountLoginRef = ref(null);

  // 响应式变量，表示checkbox是否选中
  const isAgree = ref(false);

  const handleCheckboxChange = (event) => {
    isAgree.value = event.detail.value.length > 0;
  };

  // 组件 props 定义
  const props = defineProps({
    agreeStatus: {
      type: Boolean,
      default: false,
    },
  });

  // 自定义事件定义
  const emits = defineEmits(['onConfirm']);

  // 数据状态
  const state = reactive({
    model: {
      username: '',
      password: '',
    },
  });

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const { code, data } = await AuthUtil.getInfo();
      if (code === 0) {
        setTimeout(() => {
          uni.reLaunch({ url: '/pages/index/index' });
        }, 500); // 延迟 500ms，避免页面加载超时
      }
    } catch (error) {
      console.error('获取用户信息失败', error);
    }
  };

  // 页面跳转
  const navigateToPage = (url) => {
    uni.navigateTo({ url });
  };

  // 账号登录
  const submitLogin = async () => {
    if (!isAgree.value) {
      return uni.showToast({
        title: "请阅读并勾选下方协议",
        icon: 'none',
      });
    }

    const isValid = await accountLoginRef.value?.validate().catch(() => null);
    if (!isValid) return;

    try {
      const { code, data } = await AuthUtil.login(state.model);
      if (code === 0) {
        await DictUtils.fetchAndCacheDictData();
        setTimeout(() => {
          uni.reLaunch({ url: '/pages/index/index' });
        }, 500); // 延迟 500ms，避免页面加载超时
      }
    } catch (error) {
      console.error('账号登录失败', error);
    }
  };

  // 拦截物理返回键
  const interceptBack = () => {
    uni.addInterceptor('navigateBack', {
      invoke() {
        return false; // 拦截返回
      },
    });
  };

  // 在组件挂载时注册事件监听器
  onMounted(() => {
    getUserInfo();  // 页面加载时获取用户信息
    interceptBack();  // 拦截物理返回键
  });

  // 组件卸载时移除拦截
  onUnmounted(() => {
    uni.removeInterceptor('navigateBack');
  });

</script>

<style lang="scss" scoped>
  @import './index.scss';

  // 定义 CSS 变量，统一管理颜色和字体大小
  :root {
    --primary-color: #fc4b01;
    --font-size-large: 42rpx;
    --font-size-medium: 28rpx;
    --font-size-small: 0.8125rem;
  }

  // 外层容器样式
  .container {
    height: 100vh;
    background-color: #fff;
  }

  // 背景图样式
  .img-a {
    width: 100%;
    height: 450rpx;
    background-image: url(/static/login_back.jpg);
    background-size: cover;
  }

  // 登录区域样式
  .login-view {
    width: 100%;
    position: relative;
    margin-top: -120rpx;
    background-color: #fff;
    border-radius: 8% 8% 0 0;
  }

  .t-login {
    width: 600rpx;
    margin: 0 auto;
    font-size: var(--font-size-medium);
    padding-top: 80rpx;
  }

  .t-b {
    text-align: left;
    color: #fff;
    padding: 130rpx 0 0 70rpx;
    font-size: 42rpx;
    font-weight: bold;
    line-height: 70rpx;
  }

  .head-box .head-title,
  .head-box .head-title-active {
    font-size: var(--font-size-medium);
  }

  .login-button{
    color: #fff;
    background: linear-gradient(90deg, var(--primary-color), var(--primary-color));
    border-radius: 0.875rem;
  }

  .tcp-text {
    color: #3dc2ff;
  }
</style>
